<?php
declare (strict_types=1);

namespace app\service;

use app\model\Goods;
use app\model\GoodsColorParam;
use app\model\GoodsLabel;
use app\model\GoodsMatchParam;
use app\model\GoodsSizeParam;
use app\model\GoodsSmallImages;
use app\model\MatchParam;
use app\model\TUserMatchParam;
use app\model\UserDetails;
use app\model\UserFenggeScore;
use app\traits\ServiceTrait;
use app\util\CacheHelper;
use app\util\TaobaoApiUtil;
use Exception;
use think\facade\Db;

/**
 * GoodsService
 * Class GoodsService
 * @package app\service
 */
class GoodsService
{
    //模型，带命名空间
    public static $model = 'app\model\Goods';
    //模型主键
    public static $pk = 'id';
    //name字段名称
    public static $name = 'title';

    use ServiceTrait;

    /**
     * 添加商品
     * @param $data
     * @return array
     */
    public static function add($data)
    {
        $goods = $data['goods'];
        $params = $data['params'];
        $colors = $data['colors'];
        $sizes = $data['sizes'];
        $labels = $data['labels'];
        $table_goods = Goods::$_table;
        $table_goods_color_param = GoodsColorParam::$_table;
        $table_goods_label = GoodsLabel::$_table;
        $table_match_param = MatchParam::$_table;
        $table_goods_match_param = GoodsMatchParam::$_table;
        $table_goods_size_param = GoodsSizeParam::$_table;
        $table_goods_small_images = GoodsSmallImages::$_table;
        $table_user_match_param = TUserMatchParam::$_table;
        $goodsExist = Goods::where(['tb_goods_id' => $goods['tbGoodsId']])->find();
        if (!empty($goodsExist)) throw new Exception('该商品已经存在');

        $date = date('Y-m-d H:i:s');
        $goodsData = [
            'tb_goods_id' => $goods['tbGoodsId'],
            'pict_url' => $goods['pictUrl'],
            'tbk_item_url' => $goods['tbkItemUrl'],
            'title' => $goods['title'],
            'shop_type_name' => $goods['shopTypeName'],
            'zk_final_price' => $goods['zkFinalPrice'],
            'price' => $goods['price'],
            'shop_type' => $goods['shopType'],
            'shop_name' => $goods['shopName'],
            'category_id' => $goods['categoryId'],
            'category_sup_id' => $goods['tbGoodsId'],
            'coupon_info' => $goods['categorySupId'],
            'max_commission_rate' => $goods['maxCommissionRate'],
            'coupon_click_url' => $goods['couponClickUrl'],
            'create_time' => $date,
            'update_time' => $date,
            'tbk_tkl_url' => '',
        ];
        $goodsId = Db::name($table_goods)->insertGetId($goodsData);
        if (!$goodsId) {
            throw new Exception('添加失败');
        }
        $goodsSmallImages = $goods['smallImages'];
        $img_url = implode(',', $goodsSmallImages);
        $detail_detail_url = $data['detailImgList'];

        $detail_img_url = '';
        foreach ($detail_detail_url as $detail_url) {
            $detail_img_url .= $detail_url['pictUrl'] . ',';
        }
        $detail_img_url = rtrim($detail_img_url, ',');
        $goodsImagesData = [
            'goods_id' => $goodsId,
            'img_url' => $img_url,
            'detail_img_url' => $detail_img_url,
        ];
        Db::name($table_goods_small_images)->insert($goodsImagesData);

        $goodsColorData = [];
        foreach ($colors as $color) {
            $goodsColorData[] = [
                'goods_id' => $goodsId,
                'name' => $color['name'],
                'color_id' => $color['colorId'],
                'pict_url' => $color['pictUrl'],
            ];
        }
        Db::name($table_goods_color_param)->insertAll($goodsColorData);

        $goodsLabelData = [];
        foreach ($labels as $label) {
            if (mb_strlen($label['label_name']) > 8) throw new Exception('标签名称不能超过8个字');
            $goodsLabelData[] = [
                'goods_id' => $goodsId,
                'label_name' => $label['label_name'],
                'reason' => $label['reason'],
            ];
        }
        Db::name($table_goods_label)->insertAll($goodsLabelData);

        $goodsParamsData = [];
        $seasonData = '';
        $subCategoryId = 0;
        $match_group_id = [];
        foreach ($params as $param) {
            $subCategoryId = $param['subCategoryId'];
            if ($param['matchGroupId'] == 358) {
                $seasonData = $param['paramVal'];
            }
            $group = Db::name($table_match_param)->where(['id' => $param['matchGroupId']])->column('group_id');
            $match_group_id[] = $group[0];
            $goodsParamsData[] = [
                'goods_id' => $goodsId,
                'sub_category_id' => $param['subCategoryId'],
                'match_group_id' => $group[0],
                'param_val' => $param['paramVal'],
            ];
        }
        $groupIdsOld = [];
        if ($subCategoryId) {
            $groupIdsOld = Db::name($table_user_match_param)->where(['sub_category_id' => $subCategoryId])->column('match_group_id');
        }
        $exceptGroupIds = config('goods.match_param.groupIds');
        $addGroupIds = array_diff($match_group_id, $exceptGroupIds); // 提交的数据
        if (!empty($addGroupIds)) {
            $addGroupIds = array_unique($addGroupIds);
        }
        $groupIdsOlds = [];
        if (!empty($groupIdsOld)) {
            $groupIdsOld = array_unique($groupIdsOld);
            $groupIdsOlds = array_diff($groupIdsOld, $exceptGroupIds); // 原始的数据
        }

        if ($seasonData) {
            Db::name($table_goods)->where(['id' => $goodsId])->update(['season' => $seasonData]);
        }
        Db::name($table_goods_match_param)->insertAll($goodsParamsData);

        if (!empty($groupIdsOlds)) {
            $ratio = bcdiv(count($addGroupIds) . '', count($groupIdsOlds) . '', 2);
            Db::name($table_goods_match_param)->where(['goods_id' => $goodsId])->update(['ratio' => $ratio]);
        }

        $goodsSizesData = [];
        foreach ($sizes as $param) {
            $goodsSizesData[] = [
                'goods_id' => $goodsId,
                'name' => $param['name'],
                'size_id' => $param['sizeId'],
                'create_time' => $date,
                'update_time' => $date,
            ];
        }
        Db::name($table_goods_size_param)->insertAll($goodsSizesData);

        $cache = new CacheHelper();
        $key = config('cachekeys.goodsid_all');
        $cache->sadd($key, $goods['tbGoodsId']);
    }

    /**
     * 修改商品
     * @param $data
     * @return array
     */
    public static function edit($data)
    {
        $goodsId = $data['goods']['goodsId'] ?? 0;
        $goods = Goods::where(["id" => $goodsId])->find();
        if (empty($goods)) {
            throw new Exception('没有数据');
        }
        $params = $data['params'];
        $colors = $data['colors'];
        $sizes = $data['sizes'];
        $labels = $data['labels'];

        $date = date('Y-m-d H:i:s');

        $goodsColorData = [];
        foreach ($colors as $color) {
            $goodsColorData[] = [
                'goods_id' => $goodsId,
                'name' => $color['name'],
                'color_id' => $color['colorId'],
                'pict_url' => $color['pictUrl'],
            ];
        }
        // 先删除，再添加
        GoodsColorParam::where(["goods_id" => $goodsId])->delete();
        GoodsColorParam::insertAll($goodsColorData);

        $goodsLabelData = [];
        foreach ($labels as $label) {
            if (mb_strlen($label['label_name']) > 8) throw new Exception('标签名称不能超过8个字');
            $goodsLabelData[] = [
                'goods_id' => $goodsId,
                'label_name' => $label['label_name'],
                'reason' => $label['reason'],
            ];
        }
        // 先删除，再添加
        GoodsLabel::where(["goods_id" => $goodsId])->delete();
        GoodsLabel::insertAll($goodsLabelData);

        $goodsParamsData = [];
        $seasonData = '';
        $subCategoryId = 0;
        $match_group_id = [];
        foreach ($params as $param) {
            if (empty($param['paramVal'])) continue;
            $subCategoryId = $param['subCategoryId'];
            if ($param['matchGroupId'] == 358) {
                $seasonData = $param['paramVal'];
            }
            $group = MatchParam::where(['id' => $param['matchGroupId']])->column('group_id');
            $match_group_id[] = $group[0];
            $goodsParamsData[] = [
                'goods_id' => $goodsId,
                'sub_category_id' => $param['subCategoryId'],
                'match_group_id' => $group[0],
                'param_val' => $param['paramVal'],
            ];
        }
        $groupIdsOld = [];
        if ($subCategoryId) {
            $groupIdsOld = TUserMatchParam::where(['sub_category_id' => $subCategoryId])->column('match_group_id');
        }
        $exceptGroupIds = config('goods.match_param.groupIds');
        $addGroupIds = array_diff($match_group_id, $exceptGroupIds); // 提交的数据
        if (!empty($addGroupIds)) {
            $addGroupIds = array_unique($addGroupIds);
        }
        $groupIdsOlds = [];
        if (!empty($groupIdsOld)) {
            $groupIdsOld = array_unique($groupIdsOld);
            $groupIdsOlds = array_diff($groupIdsOld, $exceptGroupIds); // 原始的数据
        }

        if ($seasonData) {
            Goods::where(['id' => $goodsId])->update(['season' => $seasonData]);
        }

        // 先删除，再添加
        GoodsMatchParam::where(["goods_id" => $goodsId])->delete();
        GoodsMatchParam::insertAll($goodsParamsData);

        if (!empty($groupIdsOlds)) {
            $ratio = bcdiv(count($addGroupIds) . '', count($groupIdsOlds) . '', 2);
            GoodsMatchParam::where(['goods_id' => $goodsId])->update(['ratio' => $ratio]);
        }

        $goodsSizesData = [];
        foreach ($sizes as $param) {
            $goodsSizesData[] = [
                'goods_id' => $goodsId,
                'name' => $param['name'],
                'size_id' => $param['sizeId'],
                'create_time' => $date,
                'update_time' => $date,
            ];
        }

        // 先删除，再添加
        GoodsSizeParam::where(["goods_id" => $goodsId])->delete();
        GoodsSizeParam::insertAll($goodsSizesData);
    }


    /**
     * 过滤非淘宝客和已添加的商品
     * @param $ids
     * @return array
     */
    public static function checkGoods($ids)
    {
        $taobaoList = TaobaoApiUtil::getItemInfo($ids);

        $data = [];
        $cache = new CacheHelper();
        $key = config('cachekeys.goodsid_all');
        foreach ($taobaoList as $v) {
            $hasCache = $cache->sismember($key, $v->num_iid);
            if ($hasCache) {
                continue;
            }
            $data[] = $v->num_iid;
        }
        return $data;
    }

    /**
     * 获取商品库
     */
    public static function getGoodsList($param)
    {
        $title = $param['title'];
        if (!empty($title)) {
            $lastGoodsList = Goods::where([['title', 'like', '%' . $param['title'] . '%']])
                ->field(['id', 'pict_url', 'title', 'price', 'zk_final_price'])
                ->order('create_time', 'desc')
                ->paginate(['page' => $param['page'], 'list_rows' => $param['pageSize']])
                ->toArray();
        } else {
            $lastGoodsList = Goods::field(['id', 'pict_url', 'title', 'price', 'zk_final_price'])
                ->order('create_time', 'desc')
                ->paginate(['page' => $param['page'], 'list_rows' => $param['pageSize']])
                ->toArray();
        }
        return json_ok($lastGoodsList, 200);
    }

    /**
     * 获取单个商品图片
     */
    public static function getGoodsDetail($goodsId)
    {
        $sub_category_ids = GoodsMatchParam::where(['goods_id' => $goodsId])->column('sub_category_id');
        if (empty($sub_category_ids)) {
            return json_error(100, '没有数据');
        }
        $sub_category_id = $sub_category_ids[0];
        $detail = MatchParamService::getMatchBySubCategory($sub_category_id, $goodsId);

        $chima = GoodsSizeParam::where(['goods_id' => $goodsId])->field(['name', 'size_id'])->select()->toArray();
        $color = GoodsColorParam::where(['goods_id' => $goodsId])->field(['name', 'color_id', 'pict_url'])->select()->toArray();

        $images = GoodsSmallImages::where(['goods_id' => $goodsId])->find();
        if (empty($images)) {
            return json_error(100, '没有数据');
        }
        $imagesData = [];
        $img_url = $images['img_url'];
        $detail_img_url = $images['detail_img_url'];
        $imagesData['img_url'] = explode(',', $img_url);
        $imagesData['detail_img_url'] = explode(',', $detail_img_url);

        $goodsLabel = GoodsLabel::where(['goods_id' => $goodsId])->field(['label_name', 'reason'])->select()->toArray();
        $list['subCategoryId'] = $sub_category_id;
        $list['chima'] = $chima;
        $list['color'] = $color;
        $list['detail'] = $detail;
        $list['imgs'] = $imagesData;
        $list['labels'] = $goodsLabel;
        return json_ok($list, 200);
    }
}
